﻿using System.Linq;
using UnityEngine;

namespace GameEntry
{
    /// <summary>
    /// 对象容器 编辑器依赖odin inspector 自行导入
    /// </summary>
    public sealed class ObjectReferenceCollection : MonoBehaviour
    {
        [SerializeField]
        private StringObjectDictionary dict = new StringObjectDictionary();

        /// <summary>
        /// 返回泛型实例
        /// </summary>
        public T Get<T>(string key) where T : Object
        {
            return dict.TryGetValue(key, out var obj) ? obj as T : null;
        }

        /// <summary>
        /// 返回Object实例
        /// </summary>
        public Object GetObject(string key)
        {
            return dict.TryGetValue(key, out var obj) ? obj : null;
        }

        /// <summary>
        /// 是否包含指定的key
        /// </summary>
        public bool ContainsKey(string key)
        {
            return dict.ContainsKey(key);
        }

        #region [Editor]

#if UNITY_EDITOR

        public void Add(string key, Object value)
        {
            dict.Add(key, value);
        }

#if ODIN_INSPECTOR
        [Sirenix.OdinInspector.HorizontalGroup("Split", 0.5f)]
        [Sirenix.OdinInspector.Button("删除空引用", Sirenix.OdinInspector.ButtonSizes.Large), Sirenix.OdinInspector.GUIColor(0.4f, 0.8f, 1)]
#endif
        private void DeleteMissingReference()
        {
            var hashSet = (from pair in dict where pair.Value == null select pair.Key).ToList();

            foreach (var key in hashSet)
                dict.Remove(key);
        }

#if ODIN_INSPECTOR
        [Sirenix.OdinInspector.VerticalGroup("Split/right")]
        [Sirenix.OdinInspector.Button("全部删除", Sirenix.OdinInspector.ButtonSizes.Large), Sirenix.OdinInspector.GUIColor(0, 1, 0)]
#endif
        private void DeleteAllReference()
        {
            dict.Clear();
        }
#endif

        #endregion
    }
}